package chaoyue.study.juc;

import chaoyue.study.ThreadUtils;

import java.util.concurrent.FutureTask;

/**
 * FutureTask可以响应中断
 * 调用cancel方法会导致原有任务抛出CancellationException异常
 */
public class FutureTaskTest2 {
    public static void main(String[] args) throws Exception {
        FutureTask<String> task1 = new FutureTask<>(() -> {
            try {
                Thread.sleep(Integer.MAX_VALUE);
            } catch (InterruptedException e) {
                System.out.println("task1 interrupted");
            }
            System.out.println("task1 finish");
            return "success";
        });
        Thread t1 = new Thread(task1);
        t1.start();

        ThreadUtils.sleep();
        // 任务取消
        task1.cancel(true); // true表示中断正在执行的任务
        // 已取消的任务获取任务运行结果会抛出CancellationException
        System.out.println(task1.get());
    }
}
